<template>
  <div class="list-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ moduleName }}管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ moduleName }}列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 筛选表单 -->
    <el-card shadow="never" class="filter-card">
      <el-form :model="filterForm" ref="filterFormRef" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" @click="handleAdd" :icon="Plus">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete" :icon="Delete" :disabled="!selectedRows.length">
        批量删除
      </el-button>
      <el-button type="warning" @click="handleExport" :icon="Download">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <el-card shadow="never" class="table-card">
      <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="240" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="price" label="单价" width="80" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Delete, Download} from '@element-plus/icons-vue'
import {axiosGet} from "@/utils/axios-utils.js";
import {useUserStore} from "@/stores/index.js";

const router = useRouter()

// 模块名称 - 根据实际模块修改
const moduleName = '产品'

// 筛选表单
const filterForm = reactive({
  username: '',
  status: '',
  dateRange: []
})

const filterFormRef = ref(null)

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})
const userStore = useUserStore()
//获取表格数据
const fetchTableData = () => {
  loading.value = true
  axiosGet('api/product')
      .then(ret=>{
    if (ret.code == "ok"){
      tableData.value = ret.data;
      console.log("产品：",ret.data)
    }
    loading.value=false;
  })

  axiosGet('/api/users', {
    params: {
      page: pagination.current,
      size: pagination.size,
      username: filterForm.username,
      status: filterForm.status,
      startDate: filterForm.dateRange?.[0],
      endDate: filterForm.dateRange?.[1]
    }
  })
      .then(res => {
        if (res.code === 'ok') {
          tableData.value = res.data || []
          pagination.total = res.total || 0
        } else {
          ElMessage.error(res.message || '获取用户数据失败')
        }
      })
      .catch(err => {
        console.error('获取用户数据失败', err)
        ElMessage.error('数据加载失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.size = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  fetchTableData()
}

// 查询
const handleSearch = () => {
  pagination.current = 1
  fetchTableData()
}

// 重置
const resetFilter = () => {
  filterFormRef.value.resetFields()
  handleSearch()
}

// 新增
const handleAdd = () => {
  router.push('/product/add')
}

// 编辑
const handleEdit = (row) => {
  router.push(`/product/edit/${row.id}`)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除用户 ${row.username} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchTableData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) return

  const usernames = selectedRows.value.map(item => item.username).join(', ')
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 个用户吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`成功删除用户: ${usernames}`)
    fetchTableData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 导出
const handleExport = () => {
  ElMessage.success('导出数据')
}

function loadUserData() {
  // axiosGet('hello')
  //     .then(ret=>console.log())
}

// 初始化数据
onMounted(() => {
  fetchTableData()
  loadUserData()
})
</script>

<style scoped>
.list-container {
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-card :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 16px;
    width: 100%;
  }

  .filter-card :deep(.el-form-item__content) {
    width: 100%;
  }

  .operation-buttons .el-button {
    margin-bottom: 10px;
  }
}
</style>